package unv.esiag.uchiha.semaphore;

import java.util.Vector;

public class Semaphore {
	private int value;
	private Vector<Thread> threads;
	private Thread threadToAwake;
	/**
	 * constructeur
	 */
	public Semaphore() {
		this(1);
	}
	/**
	 * constructeur
	 * @param val
	 */
	public Semaphore(int val) {
		value = val;
		threads = new Vector<Thread>();
		threadToAwake = null;
	}
	/**
	 * 
	 * @return
	 */
	public int getValue() {
		return value;
	}
	/**
	 * arret de la possibilité de lecture
	 */
	synchronized public void stop(){
		value--;
		if(value < 0){
			threads.add(Thread.currentThread());
			do{
				try{
					wait();
				}catch(Exception e){
					e.printStackTrace();
				}
			}while(Thread.currentThread() != threadToAwake);
		}
	}
	/**
	 * signale de la possibilité de lecture
	 */
	synchronized public void signal(){
		value++;
		if(value <= 0){
			threadToAwake = threads.remove(0);
			notifyAll();
		}
	}
}
